import {
  Component,
  OnInit,
  Input,
  OnChanges,
  Output,
  EventEmitter,
} from '@angular/core';
import { UploadOptions, UploadFile } from './interface';
import { UploaderService } from './upload.service';

@Component({
  selector: 'fui-upload',
  templateUrl: './upload.component.html',
  providers: [UploaderService],
})

export class UploadComponent implements OnInit, OnChanges {
  /** Upload url address. */
  @Input() action: string;

  /** Support file types. */
  @Input() fileTypes: string[];

  /** File size limit in kb. */
  @Input() fileSize: number;

  /** Error messge when file size limit is exceeded. */
  @Input() fileSizeErrorText: string;

  /** Error message when choosing file whose type is not supported. */
  @Input() fileTypesErrorText: string;

  /** Upload tip message. */
  @Input() uploadTips: string;

  /** Show upload tip message. */
  @Input() showUploadTip = true;

  /** Emit uploaded file. */
  @Output() uploadFileChange = new EventEmitter<File | UploadFile>();

  constructor(
    private uploaderService: UploaderService,
  ) { }

  private updateUploadOptions() {
    const uploadOptions: UploadOptions = {
      action: this.action,
      fileTypes: this.fileTypes,
      fileSize: this.fileSize,
      fileSizeErrorText: this.fileSizeErrorText,
      fileTypesErrorText: this.fileTypesErrorText,
    };
    this.uploaderService.uploadOptions = uploadOptions;
  }

  ngOnChanges() {
    this.updateUploadOptions();
  }

  ngOnInit() {
    this.uploaderService.fileSubj.subscribe((file: File | UploadFile) => {
      this.uploadFileChange.emit(file);
    });
  }
}
